
<template>
    <div class="page-catalogue" v-loading="loading">
        <div class="page-title" v-if="hideStep">{{ moocDetail.title }}</div>
        <div class="flex-between">
            <div class="litter-head-title">目录与内容</div>
            <el-button class="srt-el-button srt-el-button-h32" @click="handleAddChild">+添加目录</el-button>
        </div>
        <template v-if="folderData.length">
            <el-tree ref="folderTreeRef" :data="folderData" node-key="catalogueId" v-loading="loading" draggable
                @node-click="checkClick"
                @node-drop="handleDrop" :allow-drop="allowDrop" :expand-on-click-node="true" :auto-expand-parent="true"
                :default-expand-all="false" :render-after-expand="false" :icon="ArrowRight" class="folder-tree"
                :indent="20" :props="defaultProps" empty-text="暂无课程目录">
                <template #default="{ node, data }">
                    <div :class="['catalogue-tag', fmtCatalogue(data.tag, data.catalogueType)]" v-show="!data.editing && !data.isEmpty">
                        <span class="title">
                            <span class="title-name">
                                <ellipsis :content="data.catalogueName"/>
                            </span>
                            <!-- <span class="show-subtitle" v-if="handleSubTitle(data)">字幕</span> -->
                        </span>
                        <div @click.stop>
                            <el-button class="srt-el-button srt-el-button--link srt-el-button-h28 button-left-margin"
                                @click="handleRename(data)" v-if="data.catalogueType === 0">重命名</el-button>
                            <el-button class="srt-el-button srt-el-button--link srt-el-button-h28"
                                @click="handleEdit(data)" v-if="data.catalogueType === 1">编辑</el-button>
                            <el-button class="srt-el-button srt-el-button--link srt-el-button-h28"
                                v-if="node.level < 3 && data.catalogueType === 0"
                                @click="handleAddChild(data)">添加子目录</el-button>
                            <el-popover
                                v-if="node.level < 4 && data.catalogueType === 0"
                                trigger="hover"
                                placement="bottom-end"
                                width="104px"
                                popper-class="folder-popover"
                                :show-arrow="false"
                                :offset="0"
                                :teleported="false">
                                <template #reference>
                                    <el-button class="srt-el-button srt-el-button--link srt-el-button-h28 mar-r12">添加内容</el-button>
                                </template>
                                <ul class="folder-popover-list">
                                    <li @click="handleAddMaterial(data)">添加素材</li>
                                    <li @click="handleAddContent(data)">添加讨论</li>
                                </ul>
                            </el-popover>
                            <!-- <el-button class="srt-el-button srt-el-button--link srt-el-button-h28" v-if="(!data.children?.length || data.children[0].catalogueType === 1 || data.children[0].isEmpty) && data.catalogueType === 0">添加内容</el-button> -->
                            <!-- <el-button class="srt-el-button srt-el-button--link srt-el-button-h28"
                                v-if="data.catalogueType === 1" @click="handlePreview(data)">预览</el-button> -->
                            <el-button class="srt-el-button srt-el-button--link srt-el-button-h28"
                                @click="handleDelete(data)">删除</el-button>
                        </div>
                    </div>
                     <!-- 目录/课件编辑状态 添加、重命名框 -->
                     <div class="catalogue-tag catalogue-editing" v-if="data.editing && !data.isEmpty" @click.stop>
                        <el-form
                            ref="ruleFormRef"
                            :model="data"
                            label-width="0px"
                            class="catalogue-form"
                            @validate="(prop, isValid) => catalogueValidate(isValid, data)"
                            @submit.prevent
                        >
                            <!-- required: true, 
                                    min: 2, 
                                    max: data.catalogueType == 0 ? 30 : 50,
                                    message: `请输入2~${data.catalogueType == 0 ? 30 : 50}个字`,
                                    trigger: 'blur' -->
                            <!-- required: true,
                                    validator: data.catalogueType == 0 ? nameRule : nameRule2,
                                    trigger: 'blur' -->
                            <el-form-item label="" prop="catalogueName" 
                                :rules="[{
                                    required: true,
                                    validator: data.catalogueType == 0 ? nameRule : nameRule2,
                                    trigger: 'change'}]">
                                <el-input
                                    class="edit-input" 
                                    type="text" 
                                    :maxlength="data.catalogueType == 0 ? 30 : 50" 
                                    show-word-limit 
                                    v-model="data['catalogueName']" 
                                    placeholder="请输入" 
                                    v-focus
                                    @keyup.enter="handleCatalogue(data, node)"
                                    clearable
                                />
                            </el-form-item>
                        </el-form>
                        <div>
                            <el-button class="srt-el-button srt-el-button--link srt-el-button-h28"
                                @click="handleCatalogue(data, node)">确定</el-button>
                            <el-button class="srt-el-button srt-el-button--link srt-el-button-h28"
                                @click="cancelAdd(data, node)" v-if="data.isRename">取消</el-button>
                            <el-button class="srt-el-button srt-el-button--link srt-el-button-h28"
                                @click="confirmDelete(data)" v-else>删除</el-button>
                            
                        </div>
                     </div>
                      <!-- 目录空状态 -->
                     <div class="catalogue-tag catalogue-empty" v-if="data.isEmpty">
                        暂无内容
                     </div>
                </template>
            </el-tree>
        </template>
        <NoData v-else url="no-course.png" :showInfo="false">
            <div class="tips">暂无课程目录，请先<span class="add" @click="handleAddChild">添加目录</span></div>
        </NoData>
    </div>
    <FooterSubmit :loading="loading" @cancel="back" @submit="save"/>
    <!-- <div class="edit-submit">
        <el-button class="srt-el-button srt-el-button--cancel srt-el-button-h36 btn " @click="changeStep"
            v-if="!hideStep">上一步</el-button>
        <el-button class="srt-el-button srt-el-button-h36 btn" @click="save" type="primary">
            编辑完成
        </el-button>
        <el-button class="srt-el-button srt-el-button--primary srt-el-button-h36" v-if="moocDetail.publishState !== 1"
            @click="publish" type="primary">
            发布
        </el-button>
    </div> -->
    <!-- <ContentDialog v-model="contentShowDialog" :form="catalogueData" @add-content="confirmAddContent" /> -->
    <ContentPreviewDialog v-model="previewsDialog" :form="catalogueData" />

    <!-- 讨论弹框 -->
    <add-discuss
        v-model:visible="contentShowDialog"
        :catalogueData="catalogueData"
        @update-tree-after-edit="updateTreeAfterEdit"
        
    />

    <!-- 素材弹窗 -->
    <AddMaterial
        v-model:visible="updateMaterialDialog"
        :catalogueData="catalogueData"
        :init-sub-title-map="subTitleMap"
        @update-tree-after-edit="updateTreeAfterEdit"/>
</template>

<script setup>
import Ellipsis from '@/components/ellipsis.vue';
import NoData from '@/components/no-data.vue';
import ContentDialog from './dialog/content-dialog.vue';
import ContentPreviewDialog from '@/components/content-preview-dialog.vue';
import YanxiuMaterialDialog from '@/components/yanxiu-material-dialog.vue';
import AddDiscuss from './add-discuss.vue'
import AddMaterial from './dialog/add-material.vue';
import FooterSubmit from '@/components/common-footer-submit.vue';
import { ref, onMounted, computed, nextTick } from 'vue';
import { ArrowRight } from '@element-plus/icons-vue';
import { deepCopy, queryToJson, Debounce, treeForEach } from '@/lib/tools';
import Confirm from '@/components/confirm/confirm.js'
import { useRoute } from 'vue-router';

const route = useRoute();

const emit = defineEmits(['change-step', 'back']);

const props = defineProps({
    detail: {
        type: Object,
        default: () => {
            return {};
        }
    }
})

const defaultProps = {
    isLeaf: 'isLeaf',
    children: 'children',
    label: 'catalogueName',
    class: customNodeClass
}

// 是否显示对话框
const showDialog = ref(false);

// 讨论弹窗显隐
const discussVisible = ref(true)

// 目录内容
const catalogueData = ref({});

// 添加内容对话框
const contentShowDialog = ref(false);

const folderData = ref([]);

// 目录视频对应的字幕数组
const subTitleMap = ref({});

// 目录视频ids
const videoIds = ref([]);

const folderTreeRef = ref(null);

const loading = ref(false);

// 原始目录名称数据
const catalogueNameMap = ref({});

// 已经选中的素材
const selectedMaterials = ref([]);

// 编辑素材的弹窗
const updateMaterialDialog = ref(false);

// 课程素材详情
const moocDetail = computed(() => {
    return props.detail || {};
})

// 隐藏步骤
const hideStep = computed(() => {
    return route.query.type == 1;
})

function nameRule (rule, value = '', callback) {
    let temp = value && value.trim() || '';
    if (temp.length > 30 || temp.length < 2) {
        callback(new Error('请输入2~30个字'));
    } else {
        callback();
    }
}

function nameRule2 (rule, value = '', callback) {
    let temp = value && value.trim() || '';
    if (temp.length > 50 || temp.length < 2) {
        callback(new Error('请输入2~50个字'));
    } else {
        callback();
    }
}

// 编辑内容
function handleEdit (data) {
    
    let courseId = queryToJson().courseId || route.params.courseId;
    let type = queryToJson().type || '';
    let tabStr = queryToJson().tabStr || '';

    if (data.catalogueType === 1) {
        if (data.courseWare.contentType == 'comment') {
            catalogueData.value = Object.assign({}, data);
            contentShowDialog.value = true
        }  else {
            catalogueData.value = Object.assign({}, data);
            updateMaterialDialog.value = true;
        }
    } else {

        catalogueData.value = Object.assign({}, data);
        showDialog.value = true;
    }
}

// 添加子目录
function handleAddChild (data) {
    Debounce(function(){
        let treeData = [], lastData = {};
        if(!data) { // 如果添加根目录
            treeData = folderData.value || [];
        }else { // 如果添加子目录
            treeData = data.children || [];
        }
        lastData = treeData.length && treeData[treeData.length - 1] || {};
        if(!treeData.length || (lastData?.catalogueName && lastData?.catalogueName.length >= 2) || lastData.isEmpty) { // 编辑状态时输入框不合法不允许创建下一个
            catalogueData.value = Object.assign({}, { pid: data?.catalogueId || 0, catalogueName: '新建目录'});
            confirmSave(catalogueData.value)
        }
    },500)();
}

// 添加素材
function updateTreeAfterEdit (type, data) {
    const temp = Object.assign({}, data);
    if (type === 'append') {
        updateFolder(type, data?.pid, temp);
    } else {
        updateFolder(type, data?.catalogueId, temp);
    }
}

// 保存编辑目录
function confirmSave (formData) {
    let catalogueName = formData.contentTitle || formData.catalogueName;
    let params1 = {
        contentTitle: catalogueName,
        id: formData.catalogueId
    }
    let params2 = {
        ...formData,
        contentTitle: catalogueName,
    }
    let params = formData.catalogueId ? params1 : params2;
    let portalName = formData.catalogueId ? 'folderRename' : 'folderAdd';
    let courseId = queryToJson().courseId || route.params.courseId;
    G_transmit(portalName, {
        data: {
            ...params,
            courseId: courseId,
        }
    }).then((res) => {
        let temp = Object.assign({}, formData, {catalogueId: res.data || formData.catalogueId, catalogueName: catalogueName, catalogueType: 0});
        // 保留已有数据
        let idKey = `${temp.catalogueType}_${temp.catalogueId}`;
        catalogueNameMap[idKey] = { ...temp };
        // 更新树形结构数据
        let type = formData.catalogueId ? 'update' : 'append';
        let key = formData.catalogueId || temp.pid || 0;
        // let tip = formData.catalogueId ? '编辑成功' : '添加成功';
        // G_dispatchEvent('toast', { message: tip, type: 'success' })
        updateFolder( type, key, temp);
    }).catch((_err) => {
        console.log(_err)
    })
}


// 预览
const previewsDialog = ref(false);

function handlePreview (data) {
    catalogueData.value.title = data?.catalogueName;
    catalogueData.value.materialVO = data?.courseWare?.materialVO;
    previewsDialog.value = true;
}

// 预览
function checkClick(data) {
    if(data.catalogueType === 1 && data.tag !== 'comment') { // 目录类型{0.文件目录1课件}
        handlePreview(data);
    }
}

// 删除目录
function handleDelete (data) {
    
    let tip = data.catalogueType === 0 ? '删除目录后，将同时删除目录下的子目录和内容。删除后内容无法恢复' : '确认要删除该内容吗？';
    Confirm(
        {
            title: '温馨提示',
            text: tip
        }
    )
        .then(ret => {
            if (data.catalogueType === 0) {
                confirmDelete(data);
            } else {
                confirmDeleteContent(data);
            }
        })
        .catch(_err => {
            console.log(_err);
        })
}

// 添加内容
function handleAddContent (data) {
    // if (moocDetail.value.publishState === 1) {
    //     G_dispatchEvent('toast', { message: '课程已发布，请取消发布后再操作', type: 'error' })
    //     return;
    // }
    
    catalogueData.value = {
        ...data
    }
    contentShowDialog.value = true;
}

// 添加素材 
function handleAddMaterial (data) {
    
    catalogueData.value = {
        ...data
    }
    // let tempMaterials = [];
    // (data.children || []).forEach(item => {
    //     if (item.catalogueType === 1 && item.courseWare && item.courseWare.materialVO) {
    //         tempMaterials.push(item.courseWare.materialVO);
    //     }
    // })
    // selectedMaterials.value = tempMaterials;
    let courseId = queryToJson().courseId || route.params.courseId;
    let type = queryToJson().type || '';
    let tabStr = queryToJson().tabStr || '';
    let moocId = queryToJson().moocId || '';
    G_go({
        name: 'contentBatch',
        params: {
            courseId
        },
        query: { // 父级id
            pid: catalogueData.value.catalogueId,
            from: route.name,
            type: type,
            tabStr: tabStr,
            moocId: moocId
        }
    })
}

// 重命名操作
function handleRename(data){
    
    data.isRename = true;
    let key = `${data.catalogueType}_${data.catalogueId}`;
    catalogueNameMap[key] = { ...data };
    catalogueData.value = { ...data };
    data.editing = true;
}

function customNodeClass (data, node) {
    let error = data.isNoValidate ? 'error' : '';
    if (data.catalogueType === 0) {
        if (data.pid == 0) {
           return `catalogue-parent ${error}`
        }
        return `${error}`
    }
    if (data.catalogueType === 1) {
        return `catalogue-leaf ${error}`
    }
    return '';
}


function fmtCatalogue (tag, type) {
    if (type === 0) {
        return '';
    }
    let arr = tag && tag.split(',') || [];
    return arr.length && arr[0];
};

// 更新树
function updateFolder (type, key, data = {}) {
    console.log(type, key, data);
    let parentNode;
    let parentData;
    let emptyData = [{isEmpty: true }]; // 节点没有下级内容时手动添加的空状态子级
    switch (type) {
        case 'update': // 更新当前节点 key为当前目录节点
            resetEditState(data);
            parentNode = folderTreeRef.value.getNode(key);
            for(let key in data) {
                parentNode.data[key] = data[key];
            }
            parentNode.data.editing = false;
            parentNode.data.isRename = false;
            // parentNode.data.children = parentNode?.data?.children ? parentNode.data.children : emptyData;
            break;
        case 'append': // 后面追加目录内容 key为父节点 
            if (key === 0) { // 如果是根目录
                folderData.value.push({...data, children: emptyData});
                if (data.tag !== 'comment') {
                    folderData.value.forEach((item, i) => {
                        item.editing = i == folderData.value.length - 1;
                        let tempNode = folderTreeRef.value && folderTreeRef.value.getNode(item.catalogueId);
                        if(tempNode) {
                            tempNode.data.editing = item.editing;
                            // parentNode.data.isRename = false;
                            // tempNode.data = deepCopy(item);
                        }
                    }); // 将列表除最后一个其他都置为非编辑状态
                }
            } else {
                parentNode = folderTreeRef.value.getNode(key);
                parentData = parentNode.data;
                if (parentData.children?.length) {
                    let filterData = parentData.children.filter(i => !i.isEmpty); // 添加真实的子节点时去掉空状态占位节点
                    
                    if (data.catalogueType === 0) {
                        parentData.children = [...filterData, {...data, children: emptyData}]
                    } else {
                        parentData.children = [...filterData, {...data}]
                    }
                } else {
                    parentData.children = [{...data, children: emptyData}];
                    if (data.catalogueType === 0) {
                        parentData.children =  [{...data, children: emptyData}];
                    } else {
                        parentData.children = [{...data}]
                    }
                }
                if (data.tag !== 'comment') { 
                    parentData.children.forEach((item, i) => (item.editing = i == parentData.children.length - 1) ); // 将列表除最后一个其他都置为非编辑状态
                }
                parentNode.expand();
            }
            break;
        case 'remove':
            {
                let currentNode = folderTreeRef.value.getNode(key);
                let pNode = folderTreeRef.value.getNode(currentNode.data.pid);
                // 移除当前节点后父节点没有子级的话，添加空状态占位节点
                if(pNode){
                    let length = pNode.childNodes?.length || 0;
                    if (length <= 1) {
                        pNode.data.children = [...emptyData];
                    }
                }
                folderTreeRef.value.remove(key);
            }
            break;
        default:
            break;
    }
    setTimeout(() => {
        if ((type === 'append' || type === 'update') && data.catalogueType === 1 && data.tag === 'video') {
            getSubTitleList(data.courseWare.contentId);
        } 
    }, 1000)
}

function confirmDelete (data) {
    G_transmit('folderResourceDelete', {
        data: {
            catalogueIdList: [
                data.catalogueId
            ],
            pid: data.pid,
            pidTag: ''
        }
    }).then((res) => {
        updateFolder('remove', data.catalogueId);
        // G_dispatchEvent('toast', { message: '删除成功', type: 'success' });
    }).catch((_err) => {
        console.log(_err)
    })
}

// 删除内容
function confirmDeleteContent (data) {
    let courseId = queryToJson().courseId || route.params.courseId;
    G_transmit('courseContentCreate', {
        data: {
            contentList: [
                {
                    invalid: 1,
                    id: data.catalogueId,
                    courseWareId: data.courseWare.id
                }
            ],
            courseId,
            pid: data.pid
        }
    })
        .then((res) => {
            updateFolder('remove', data.catalogueId);
            // G_dispatchEvent('toast', { message: '删除成功', type: 'success' });
        })
        .catch((_err) => {
            console.log(_err)
        })
}

// 添加内容
function confirmAddContent (formData, item) {
    let courseId = queryToJson().courseId || route.params.courseId;
    let type = queryToJson().type || '';
    let tabStr = queryToJson().tabStr || '';
    G_go({
        name: 'content',
        params: {
            courseId,
            type: item.type
        },
        query: { // 父级id
            pid: formData.catalogueId,
            from: route.name,
            type: type,
            tabStr: tabStr
        }
    })
}

// 获取课程目录列表
function getList () {
    let courseId = queryToJson().courseId || route.params.courseId;
    loading.value = true;
    G_transmit('getFolderTree', {
        queries: {
            courseId,
            pathDeep: 5,
            showData: true,
            queryAll: true
        }
    }).then(async (res) => {
        folderData.value = treeNodeFormat(res.data)|| [];
        videoIds.value = [];
        if (folderData.value && folderData.value.length) {
            treeForEach(folderData.value, item => {
                if (item.catalogueType === 1 && item.courseWare && item.courseWare.contentId && item.tag === 'video') {
                    videoIds.value.push(item.courseWare.contentId);
                }
            })
        }
        // 获取视频字幕
        getSubTitleList();
        await nextTick();
        let pid = queryToJson().pid || '';
        if (pid) {
            expandParent(pid);
        }
    }).catch((_err) => {
        console.log(_err)
    }).finally(() => {
        loading.value = false;
    })
}

// 获取字幕列表 目录有视频获取字幕
function getSubTitleList (otherId) {
    otherId && videoIds.value.push(otherId);
    if (videoIds.value.length > 0) {
        G_transmit('subtitleSearch', {
            data: {
                materialIds: videoIds.value,
                subtitleInitType: 1
            }
        }).then(async (res) => {
            subTitleMap.value = {};
            (res.data || []).forEach(item => {
                subTitleMap.value[item.materialId] = item;
            })
        }).catch((_err) => {
            console.log(_err)
        }).finally(() => {
        })
    }
}

// 控制是否显示字幕
function handleSubTitle (data) {
    if (data.catalogueType === 1 && data.tag=== 'video' && data.courseWare.contentId && subTitleMap.value[data.courseWare.contentId]) {
        return true;
    } else {
        return false
    }
}

// 文件夹树处理
function treeNodeFormat(arr) {
    const emptyData = [{isEmpty: true, /* 空目录状态标识 */ }];
    return arr.length && arr.map((item, index) => {
        if(item.children && item.children.length){
            item.children = treeNodeFormat(item.children)
        } 
        return {
            ...item,
            children: (item.children && item.children.length) || item.catalogueType == 1 ? item.children: emptyData // 如是没有子级的目录，添加空状态占位
        }
    }) || []
}

// 展开树节点
function expandParent (pid) {
    if (pid) {
        let parentNode = folderTreeRef.value.getNode(pid);
        if (parentNode) {
            parentNode.expand();
        }
        if (parentNode.level > 1 && parentNode?.parent?.data) {
            let pid = parentNode.parent.data.catalogueId;
            expandParent(pid);
        }
    }
}

function changeStep () {
    emit('change-step', 1);
    let courseId = queryToJson().courseId;
    let tabStr = queryToJson().tabStr;
    if (courseId) {
        window.history.pushState('', '', `?courseId=${courseId}&step=1&tabStr=${tabStr || ''}`);
    } else {
        window.history.pushState('', '', `?step=1&tabStr=${tabStr || ''}`)
    }
}

// 编辑完成
function save () {
    if (route.name === 'addDesign') {
        G_transmit('bindCourseAndPublish', { // 绑定课程素材
            data: {
                moocId: route.query.moocId,
                contentType: 'course',
                contentId: route.params.courseId
            }
        }).then((res) => {
            back();
        }).catch((_err) => {
            console.log(_err)
        })
    } else {
        back();
    }
}

// 发布
function publish () {
    // if (!folderData.value.length) {
    //     G_dispatchEvent('toast', { message: '请添加课程目录', type: 'error' });
    //     return;
    // }
    Confirm(
        {
            title: '温馨提示',
            text: '确认要发布吗？'
        }
    )
        .then(ret => {
            confirmPublish();
        })
        .catch(_err => {
            console.log(_err);
        })
}

function confirmPublish () {
    let courseId = queryToJson().courseId || route.params.courseId;
    G_transmit('coursePublish', {
        queries: {
            id: courseId
        },
        silence: true
    }).then((res) => {
        G_dispatchEvent('toast', { message: '发布成功', type: 'success' });
        back();
    })
        .catch((err) => {
            // 30800503转码失败，30800504 转码中
            if (err.status && err.status.code && [30800503].includes(err.status.code)) {
                let str = ''
                let len = err.data && err.data.length || 0;
                err.data && err.data.map((item, index) => {
                    str += item;
                    if (index < len - 1) {
                        str += '、'
                    }
                })
                Confirm({
                    title: '转码失败',
                    text: () => {
                        return (
                            <div>
                                <p>课程内容转码失败，请重新添加！</p>
                                <p style="color: var(--srt-main-active-text-color)">{str}</p>
                            </div>
                        );
                    },
                    type: 'error',
                    submitText: '知道了',
                    showCancelButton: false
                }).then(ret => {
                }).catch(err => {
                    // 点击取消按钮触发
                    if (err === 'cancel') return
                })
            } else if (err.status && err.status.code && [30800504].includes(err.status.code)) {
                G_dispatchEvent('toast', { message: '课件内容正在转码中，请稍后发布！', type: 'error' });
            } else {
                G_dispatchEvent('toast', { message: err?.status?.desc || '服务开小差了～', type: 'error' });
            }
            console.log(err)
        })
}




function back () {
    if (route.query.moocId) {
        let tabStr = queryToJson().tabStr || '';
        G_go({
            name: 'manage',
            params: {
                moocId: route.query.moocId
            },
            query: {
                tabStr
            }
        })
    } else {
        emit('back');
    }
}

// 拖拽完成
function handleDrop (draggingNode, dropNode, dropType, ev) {
    let pid = draggingNode.data.pid;
    if (pid) {
        saveOrder(draggingNode.data.pid);
    }
}

// 允许拖拽的范围
function allowDrop (draggingNode, dropNode, type) {
    if (draggingNode.data.level === dropNode.data.level) {
        if (draggingNode.data.pid == dropNode.data.pid  && !draggingNode?.data?.isEmpty) {
            return type === 'prev' || type === 'next'
        } else {
            return false;
        }
    } else {
        // 不同级进行处理
        return false;
    }
}

function saveOrder (pid) {
    let parentNode = folderTreeRef.value.getNode(pid);
    let childrenList = folderData.value || [];
    if (parentNode) {
        childrenList = parentNode.data.children || [];
    }
    let paramsList = childrenList.map((item, index) => {
        return { id: item.catalogueId, orderNum: index + 1 };
    })
    G_transmit('updateOrder', {
        data: {
            items: paramsList
        }
    })
        .then((res) => {
            G_dispatchEvent('toast', { message: '移动成功', type: 'success' });
        })
        .catch((err) => {
            console.log(err)
        })
}

// 自定义 v-focus，编辑状态时自动聚焦input
const vFocus = {
    mounted: (el) => {
        el.querySelector('input').focus();
    }
}

// 目录名称校验
function catalogueValidate(isValid, data) {
    data.isNoValidate = !isValid
}


// 目录编辑框确定操作
function handleCatalogue(data, node){
    let temp = data.catalogueName && data.catalogueName.trim() || '';
    if(temp.length < 2){
        return false;
    }
    if(data.catalogueType != 1){
        confirmSave(data);
    }else{
        confirmSaveContent(data);
    }
}

// 重置树状态
function resetEditState(data) {
    data.isRename = false;
    data.editing = false;
}

// 输入框编辑态取消的操作
function cancelAdd(data, node){
    let key = `${data.catalogueType}_${data.catalogueId}`;
    data.catalogueName = catalogueNameMap[key]?.catalogueName;
    data.isNoValidate = false;
    updateFolder( 'update', data.catalogueId, data);
}

// 提交保存内容目录
function confirmSaveContent(formData) {
    let courseId = queryToJson().courseId || route.params.courseId;
    let courseWare = formData.courseWare || {};
    let params = {
        contentTitle: formData.catalogueName,
        unitValue: courseWare.unitValue,
        contentId: courseWare.contentId,
        tag: formData.tag,
        contentType: 'material',
        id: formData.catalogueId,
        courseWareId: courseWare.id
    }

    G_transmit('courseContentCreate', {
        data: {
            contentList: [
                {
                    ...params
                }
            ],
            courseId: courseId,
            pid: formData.pid
        }
    })
    .then((res) => {
        let temp = Object.assign({}, formData, {catalogueId: formData.catalogueId, catalogueName: formData.catalogueName, catalogueType: 1});
        G_dispatchEvent('toast', { message: '重命名成功', type: 'success' })
        updateFolder( 'update', formData.catalogueId, temp);
    })
    .catch((_err) => {
    })
}


onMounted(() => {
    getList();
})


</script>

<style lang="scss" scoped>

@mixin img-style() {
    content: '';
    width: 18px;
    height: 18px;
    display: inline-block;
    vertical-align: middle;
    margin-right: 8px;
    margin-left: 7px;
}

.page-catalogue {
    background: #ffffff;
    padding: 0px 120px 20px;
    min-height: 456px;
    margin-bottom: 30px;

    .no-data {
        padding-top: 40px;
    }

    .tips {
        font-size: 14px;
        color: var(--srt-color-gray);

        .add {
            cursor: pointer;
            color: var(--srt-main-active-text-color);
        }
    }
}

.folder-tree {
    margin-top: 20px;

    :deep(.el-tree-node) {
        font-size: 14px;
    }

    :deep(.catalogue-leaf) {
        .el-tree-node__expand-icon {
            display: none;
        }
    }

    :deep(.el-tree-node__expand-icon:not(.is-leaf)) {
        color: var(--main-text-color);
    }

    :deep(.el-tree-node__content) {
        height: 50px;
        color: var(--main-text-color);
        border-bottom: 1px solid #E0E2E4;

        &:hover {
            background: #E7F1FF;
            border-radius: 4px;
        }
    }

    :deep(.el-tree-node__expand-icon) {
        margin-left: 4px;
    }

    :deep(.el-tree-node:focus) {
        &.catalogue-parent>.el-tree-node__content {
            background-color: #F7F9FA;
        }

        &>.el-tree-node__content {
            background-color: transparent;
        }
    }
}

:deep(.catalogue-parent) {
    padding-bottom: 20px;

    &>.el-tree-node__content {
        height: 50px;
        background: #F7F9FA;
        border-radius: 4px;
        font-weight: bold;
        color: var(--main-text-color);
        border: none;
    }
}

:deep(.active) {
    &>.el-tree-node__content {
        background: #E7F1FF;
    }
}

.catalogue-tag {
    flex: 1;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-right: 20px;
    margin-left: 2px;
    width: 100%;
    // overflow: hidden;

    .title {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        flex: 1;
        overflow: hidden;
        .title-name {
            display: inline-block;
            max-width: calc(100% - 200px);
            // flex: 1;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        .show-subtitle {
            color: #47698C;
            margin-left: 4px;
            padding: 0 4px;
            background: #EFF0F2;
            border-radius: 4px;
            line-height: 20px;
        }
    }

    &.doc, &.docx {
        &::before {
            @include img-style();
            background: url('~@/assets/img/resource-type/doc.png') no-repeat;
            background-size: contain;
        }
    }
    &.ppt, &.pptx {
        &::before {
            @include img-style();
            background: url('~@/assets/img/resource-type/ppt.png') no-repeat;
            background-size: contain;
        }
    }
    &.xls, &.xlsx{
        &::before {
            @include img-style();
            background: url('~@/assets/img/resource-type/excel.png') no-repeat;
            background-size: contain;
        }
    }

    &.img {
        &::before {
            @include img-style();
            background: url('~@/assets/img/resource-type/img.png') no-repeat;
            background-size: contain;
        }
    }

    &.files {
        &::before {
            @include img-style();
            background: url('~@/assets/img/resource-type/files.png') no-repeat;
            background-size: contain;
        }
    }

    &.pdf {
        &::before {
            @include img-style();
            background: url('~@/assets/img/resource-type/pdf.png') no-repeat;
            background-size: contain;
        }
    }

    &.audio {
        &::before {
            @include img-style();
            background: url('~@/assets/img/resource-type/audio.png') no-repeat;
            background-size: contain;
        }
    }

    &.video {
        &::before {
            @include img-style();
            background: url('~@/assets/img/resource-type/video.png') no-repeat;
            background-size: contain;
        }
    }

    &.rest,
    &.unknown {
        &::before {
            @include img-style();
            background: url('~@/assets/img/resource-type/rest.png') no-repeat;
            background-size: contain;
        }
    }

    &.comment {
        &::before {
            @include img-style();
            background: url('~@/assets/img/resource-type/comment.png') no-repeat;
            background-size: contain;
        }
    }

    &.catalogue {
        &::before {
            display: none;
        }
    }
}

.catalogue-editing{
    justify-content: flex-start;
    cursor: default;
    -webkit-user-drag: element;
    input{
        cursor: text;
        user-select: text;
    }
}

.edit-submit {
    padding: 30px 0px 0px;
    text-align: center;

    .btn {
        width: 76px;
        margin-right: 8px;
    }
}

.page-title {
    text-align: center;
    font-size: 18px;
    line-height: 28px;
    font-weight: bold;
    padding-top: 20px;
    margin-bottom: 25px;

}
.flex-between {
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.litter-head-title {
    font-size: 18px;
    font-weight: bold;

    &::before {
        content: '';
        background: var(--srt-main-active-text-color);
        width: 4px;
        height: 18px;
        background-size: contain;
        display: inline-block;
        margin-right: 10px;
        vertical-align: middle;
        transform: translateY(-1px);
    }
}

.catalogue-editing{
    display: flex;
    justify-content: flex-start;
    cursor: default;
    -webkit-user-drag: element;
    input{
        cursor: text;
        user-select: text;
    }
}
:deep(.catalogue-form .el-form-item){
    margin-bottom: 0;
}
.edit-input{
    width: 540px;
    height: 32px;
    margin-right: 20px;
}

:deep(.error){
    .el-tree-node__content{
        height: 66px !important;
        padding: 9px 0 7px 0;
        box-sizing: border-box;
        align-items: flex-start;
    }
    .catalogue-tag{
        align-items: flex-start;
    }
    .el-form-item__error{
        top:calc(100% + 6px);
    }
}

.catalogue-empty {
    justify-content: center;
    color: #999999;
}
.folder-popover-list {
    max-height: 310px;
    overflow-y: auto;
    li {
        font-weight: 400;
        font-size: 14px;
        line-height: 32px;
        text-align: center;
        margin: 3px 0;
        color: var(--color-black);
        cursor: pointer;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        &:hover {
            background: var(--color-blue-auxiliary1);
            border-radius: 4px;
        }
    }
}
.mar-r12 {
    margin-right: 12px;
}
:deep(.folder-popover) {
    padding: 6px !important;
    min-width: 74px !important;
    box-shadow: 0px 2px 12px 0px rgba(127,127,127,0.15) !important;
    border: none !important;
    z-index: 10 !important;
    .move-popover-item {
        padding: 0 10px;
        color: var(--color-black);
        height: 32px;
        line-height: 32px;
        .iconfont {
            font-size: 12px;
        }
        &:hover {
            background: #f0f5ff;
            border-radius: 4px;
        }
    }
}
</style>